package cn.itcast.servlet;

import cn.itcast.domain.Student;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;

@WebServlet("/listStudentServlet")
public class ListStudentServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //解决乱码问题
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        if(new File("D:/stu.txt").exists()){
            //若有学生信息则读取文件
            BufferedReader br = new BufferedReader(new FileReader("D:/stu.txt"));

            //创建集合，保存学生对象
            ArrayList<Student> list = new ArrayList<>();

            //循环读取，封装，添加
            String line;
            while ((line=br.readLine())!=null){
                Student stu = new Student();
                String[] arr = line.split(",");
                stu.setUsername(arr[0]);
                stu.setAge(arr[1]);
                stu.setScore(arr[2]);
                list.add(stu);
            }

            //将集合对象存入会话域后重定向
            request.getSession().setAttribute("student",list);
            response.sendRedirect(super.getServletContext().getContextPath()+"/listStudent.jsp");
        }else {
            //若无文件存在,提示信息后跳转
            response.setHeader("Refresh","2;" + super.getServletContext().getContextPath() + "/index.jsp");
            response.getWriter().print("暂无学生信息,请添加后重试,两秒钟后自动跳转");
        }
    }
}
